﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Linq;
using YaAppoint.Response;

namespace YaAppoint.Rooms
{
    /// <summary>
    /// 诊室服务
    /// </summary>
    [RemoteService(isEnabled: false)]
    public class RoomsAppService(IRepository<Room, Guid> roomRepository,
                                 AsyncQueryableExecuter queryExcuter,
                                 IRepository<Device,Guid> deviceRrepository,
                                 IMapper mapper) : ApplicationService, IRoomsAppService, ITransientDependency
    {
        private readonly IMapper _mapper = mapper;
        private readonly IRepository<Room, Guid> _roomRepository = roomRepository;
        private readonly IRepository<Device, Guid> _deviceRrepository = deviceRrepository;
        private readonly AsyncQueryableExecuter _queryExcuter = queryExcuter;

        /// <summary>
        ///  获取科室诊室列表
        /// </summary>
        public async Task<BackJson> GetDepartmentRooms(Guid depId, string? filterName, int page, int pageSize)
        {
            var query = await _roomRepository.GetQueryableAsync();
            query = query.Where(x => x.DepartmentId == depId);
            if (!string.IsNullOrEmpty(filterName))
            {
                query = query.Where(x => x.Name.Contains(filterName));
            }
            var list = await _queryExcuter.ToListAsync(query);
            var totoalCount = list.Count();
            list = list.Skip(pageSize * (page - 1)).Take(pageSize).ToList();

            return new BackJson()
            {
                code = 0,
                data = new
                {
                    totalCount = totoalCount,
                    rooms = _mapper.Map<List<Room>, List<RoomDto>>(list)
                }
            };
        }


        /// <summary>
        /// 加载诊室详情
        /// </summary>
        public async Task<BackJson> GetAsync(Guid id)
        {
            var room = await _roomRepository.GetAsync(id);
            return new BackJson()
            {
                code = 0,
                data = _mapper.Map<Room, RoomDto>(room)
            };
        }

        /// <summary>
        /// 提交新建
        /// </summary>
        public async Task<BackJson> SubmitCreate(CreateRoomDto dto, Guid depId)
        {
            Room room = _mapper.Map<CreateRoomDto, Room>(dto);
            room.DepartmentId = depId;
            room.Code = dto.OuterCode;
            await _roomRepository.InsertAsync(room);
            return new BackJson()
            {
                code = 0,
                msg = "保存成功。"
            };
        }

        /// <summary>
        /// 提交修改
        /// </summary>
        public async Task<BackJson> SubmitEdit(RoomDto dto, Guid depId)
        {
            var room = await _roomRepository.FirstOrDefaultAsync(x => x.Id == dto.Id);
            if (room == null)
            {
                throw new BusinessException(CustomErrorCodes.RoomNotExist);
            }
            room.Name = dto.Name;
            room.Code = dto.Code;
            room.OuterCode = dto.OuterCode;
            room.IsActive = dto.IsActive;
            room.Desc = dto.Desc;
            await _roomRepository.UpdateAsync(room);
            return new BackJson()
            {
                code = 0,
                msg = "保存成功。"
            };
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        public async Task<BackJson> DeleteMany(List<Guid> idList)
        {
            foreach (var id in idList)
            {
                var room = await _roomRepository.FirstOrDefaultAsync(x=>x.Id==id);
                var devices = await _deviceRrepository.GetListAsync(x => x.RoomId==id);
                if (room != null)
                {
                    foreach (var device in devices)
                    {
                        await _deviceRrepository.DeleteAsync(device);
                    }
                }
                await _roomRepository.DeleteAsync(id);
            }
            return new BackJson()
            {
                code = 0,
                msg = "删除成功。"
            };
        }

        /// <summary>
        /// 删除
        /// </summary>
        public async Task<BackJson> Delete(Guid id)
        {
            var room = await _roomRepository.FirstOrDefaultAsync(x => x.Id == id);
            var devices = await _deviceRrepository.GetListAsync(x=>x.RoomId==id);
            if (room != null)
            {
                foreach (var device in devices)
                {
                    await _deviceRrepository.DeleteAsync(device);
                }
                await _roomRepository.DeleteAsync(id);
            }
            
            return new BackJson()
            {
                code =0,
                msg="删除成功。"
            };
        } 
    }
}
